package com.cskaoyan.demo2.controller;

import org.apache.commons.io.IOUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;


@RestController
@RequestMapping("wx/storage")
public class WxStorageFetchController {

    //http://localhost/wx/storage/fetch/1.png

    @GetMapping("fetch/{filename}")
    //表示的是获取路径中的filename的部分，赋值给对应的形参
    public void fetch(@PathVariable("filename") String filename, HttpServletResponse response) throws IOException {
        String path = "D/image";
        File file = new File(path + "/" + filename);
        if (file.exists() && file.isFile()) {
            try {
                FileInputStream fileInputStream = new FileInputStream(file);
                ServletOutputStream outputStream = response.getOutputStream();
                int length = 0;
                byte[] bytes = new byte[1024];
                while ((length = fileInputStream.read(bytes)) != -1) {
                    outputStream.write(bytes, 0, length);
                }
                return;
            } catch (FileNotFoundException e) {
                throw new RuntimeException(e);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }

        }
        response.sendError(404);
    }
}

